<template>
    <div class="container">
        <el-checkbox-group v-model="checkedList" @change="handleChange">
            <el-row :gutter="16" style="margin: 0 -8px">
                <el-col v-for="item in props.videoDataList" :key="item.id" :span="6" style="padding: 8px">
                    <div class="container_img">
                        <div class="checked">
                            <el-checkbox :label="item.id"></el-checkbox>
                        </div>
                        <div v-show="item.is_radar" class="radar_icon"></div>
                        <div class="play" @click="checkFun(item.absolute_url)"></div>
                        <el-image
                            style="width: 100%; height: 200px"
                            :src="item.thumbnail_url"
                            :initial-index="1"
                            fit="cover">
                        </el-image>
                    </div>
                    <div class="container_text">
                        <div class="tag_box">
                            <el-popover
                                v-if="item.tags?.length > 0 || item.share_tags?.length > 0"
                                :width="300"
                                trigger="hover"
                                popper-class="auto_width">
                                <template #reference>
                                    <div class="zw-el-tags">
                                        <el-tag v-for="tag in getTags(item.tags, item.share_tags, 1)" :key="tag.id">
                                            {{ tag.name }}
                                        </el-tag>
                                    </div>
                                </template>
                                <template #default>
                                    <div class="zw-el-tags">
                                        <el-tag v-for="tag in getTags(item.tags, item.share_tags, 2)" :key="tag.id">
                                            {{ tag.name }}
                                        </el-tag>
                                    </div>
                                </template>
                            </el-popover>
                        </div>
                        <div class="describe">
                            <span class="describe_text" :title="item.file_name">{{ item.file_name }}</span>
                        </div>
                        <div class="time">
                            <span>{{ item.created_at }}</span>
                            <span>上传者:{{ item.user_name || '未知' }}</span>
                        </div>
                    </div>
                    <div class="iconList">
                        <template v-for="(icon, key) in item.compilesss">
                            <div
                                v-if="item.is_radar"
                                :key="key"
                                v-auth="power[key]"
                                class="icon_item"
                                @click="selectItem(item, key)">
                                <el-tooltip class="box-item" effect="dark" :content="icon.content" placement="top">
                                    <img
                                        :id="key.toString()"
                                        :src="`/static/material/compile${icon.isShow ? 'Red' : ''}Icon${key + 1}.png`"
                                        alt=""
                                        @mouseover="item.compilesss[key].isShow = true"
                                        @mouseout="item.compilesss[key].isShow = false" />
                                </el-tooltip>
                            </div>
                            <div
                                v-if="item.is_radar == 0 && key != 0"
                                :key="key"
                                v-auth="power[key]"
                                class="icon_item"
                                @click="selectItem(item, key)">
                                <el-tooltip class="box-item" effect="dark" :content="icon.content" placement="top">
                                    <img
                                        :id="key.toString()"
                                        :src="`/static/material/compile${icon.isShow ? 'Red' : ''}Icon${key + 1}.png`"
                                        alt=""
                                        @mouseover="item.compilesss[key].isShow = true"
                                        @mouseout="item.compilesss[key].isShow = false" />
                                </el-tooltip>
                            </div>
                        </template>
                    </div>
                </el-col>
            </el-row>
        </el-checkbox-group>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="batchRemove" />

    <ShareConfiguration v-if="isShowConfiguration" :id="content_id" v-model:show="isShowConfiguration" :type="4" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted } from 'vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { useStore } from '@/store';
import bus from '@/utils/bus';
import emitter from '../common/js/mitt.js';
import { batchDownLoad, batchContentDel } from '@/api/concreation.ts';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import useClipboard from 'vue-clipboard3';
import ShareConfiguration from '@/components/common/ShareConfiguration.vue';
import { endLoading, startLoading } from '@/utils/request';

const router = useRouter();
const store = useStore();
const selectId = ref(0);
const checkedList = ref([]);
const DeletdialogRef = ref(null);
const emit = defineEmits(['submit', 'openDialog']);
const isBatch = ref(false); // 是否为批量删除
const checked1 = ref(false);
const selectKey = ref(''); // 选中编辑栏的 key
const props = defineProps(['Item', 'videoDataList', 'checkedId']);
const power = ref(['LOOK_DETAILS_VD', 'DEL_VD', 'DOW_VD', 'EDIT_VD']);
const isShowConfiguration = ref<boolean>(false);
const content_id = ref<number>(0);

const { toClipboard } = useClipboard();

const videoCheck = ref(false);
const selection = computed(() => {
    return store.getters['table'].tableData;
});
const checkListAll = ref([]);
const handleChange = (value: any) => {
    const checkedCount = value.length;
    const checkAll = checkedCount === props.videoDataList.length;
    bus.emit('change', checkedList.value);
    bus.emit('autoCheckedAll', checkAll);
    bus.emit('videoId', checkedList.value);
    store.dispatch('table', {
        tableData: value
    });
};
const clearSelection = () => {
    bus.emit('change', []);
    bus.emit('videoId', []);
    bus.emit('autoCheckedAll', false);
    store.dispatch('table', {
        tableData: []
    });
    checkedList.value = [];
};

//合并
const getTags = (arr1: any, arr2: any, type: any) => {
    if (type == 1) {
        return arr1.concat(arr2).slice(0, 4);
    } else {
        return arr1.concat(arr2);
    }
};
// 批量删除
const isBatchDel = () => {
    isBatch.value = true;
    DeletdialogRef.value.appDialog.visible = true;
};
// 删除确认弹框
const batchRemove = async () => {
    startLoading();
    try {
        if (!isBatch.value) {
            const params = {
                type: 4,
                content_ids: [selectId.value]
            };
            await batchContentDel(params);
            ElMessage.success('删除成功');
            DeletdialogRef.value.appDialog.visible = false;
            emit('submit');
        } else {
            const params = {
                type: 4,
                content_ids: checkedList.value
            };
            await batchContentDel(params);
            ElMessage.success('批量删除成功');
            DeletdialogRef.value.appDialog.visible = false;
            emit('submit');
        }
    } catch (error) {
        endLoading();
    }
};

// 复制
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const removeCheckId = () => {
    bus.off('removeCheckId');
};
// 添加全选监听事件
bus.on('removeCheckId', removeCheckId);

//编辑
const selectItem = (item: any, key: any) => {
    selectKey.value = item.compilesss[key].name;
    item.compilesss[key].isShow = true;
    if (selectKey.value == 'write') {
        const params = { ...item, type: 4, isEdit: true };
        emit('openDialog', params);
    } else if (selectKey.value == 'delete') {
        // 删除
        DeletdialogRef.value.appDialog.visible = true;
        isBatch.value = false;
        selectId.value = item.id;
    } else if (selectKey.value === 'statistics') {
        // 预览
        router.push(`/content/basematerial/statement?id=${item.id}&title=${item.title}`);
    } else if (selectKey.value == 'copy') {
        if (item.is_radar) {
            content_id.value = item.id;
            isShowConfiguration.value = true;
        } else {
            onCopy(item.absolute_url);
        }
    } else {
        // 下载
        const params = {
            material_ids: [item.id],
            material_type: 4
        };
        bus.emit('download', params);
        batchDownLoad(params).then(res => {
            const a = document.createElement('a');
            a.href = res.url;
            a.click();
            // clearSelection();
        });
    }
};
// 全选
const checkAll = (value: any) => {
    if (value) {
        props.videoDataList.forEach(item => {
            checkedList.value.push(item.id);
            store.dispatch('table', {
                tableData: checkedList,
                tableAll: true
            });
        });
        bus.emit('videoId', checkedList.value);
    } else {
        checkedList.value = [];
    }
};
// 主动暴露方法
defineExpose({ isBatchDel, clearSelection });
// 播放器弹框
const checkFun = (url: string) => {
    emitter.emit('true');
    emitter.emit('url', url);
};

watch(selection, arr => {
    checked1.value = false;
    if (arr.indexOf(props.checkedId) !== -1) {
        checked1.value = true;
    }
});

// 添加全选监听事件
bus.on('checkAll', checkAll);
onUnmounted(() => {
    store.dispatch('table', {
        tableData: [],
        tableAll: true
    });
    bus.off('checkAll', checkAll);
});

// 修改 popover 样式
const style = reactive({
    display: 'flex',
    color: '#ff6b00',
    'flex-wrap': 'wrap'
});
const tagStyle = reactive({
    border: '1px solid #ffc69e',
    padding: '0 4px',
    'white-space': 'nowrap',
    'line-height': '22px',
    margin: '0 5px 10px'
});
</script>

<style lang="scss" scoped>
.container {
    &_img {
        position: relative;

        .checked {
            position: absolute;
            left: 13px;
        }

        .radar_icon {
            position: absolute;
            top: 10px;
            right: 12px;
            width: 22px;
            height: 22px;
            background: url('@/assets/image/material/radar_red.png') no-repeat;
            background-size: 100%;
            z-index: 1;
        }

        .play {
            width: 40px;
            height: 40px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 99;
            background: url('@/assets/image/material/play.png') no-repeat;
            background-size: cover;
            cursor: pointer;
        }
    }

    &_text {
        margin-top: -4px;
        padding: 10px;
        overflow: hidden;
        border: 1px solid #eaeaea;
        border-top: none;
        box-sizing: border-box;

        .tag_box {
            height: 22px;
            overflow: hidden;
        }

        .tagList {
            width: 100%;
            height: 24px;
            overflow: hidden;
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #ff6b00;

            .tag_item {
                height: 22px;
                line-height: 22px;
                padding: 0 4px;
                background: #fff;
                border: 1px solid #ffc69e;
                border-radius: 2px;
                margin: 0 5px;
                cursor: pointer;
                white-space: nowrap;

                &:nth-child(1) {
                    margin-left: 0;
                }

                &:nth-child(n + 5) {
                    display: none;
                }
            }
        }

        .describe {
            height: 14px;
            margin: 12px 0 8px;
            line-height: 14px;
            font-size: 14px;
            display: flex;
            align-items: center;

            &_text {
                display: inline-block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

        .time {
            display: flex;
            justify-content: space-between;
            height: 18px;
            line-height: 18px;
            color: #969696;
            font-weight: 300;
            font-size: 12px;
        }
    }

    .iconList {
        display: flex;
        align-items: center;
        justify-content: space-around;
        border-radius: 2px;
        border: 1px solid #eaeaea;
        border-top: none;
        height: 40px;

        .icon_item {
            width: 19px;
            height: 19px;
            cursor: pointer;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }
}
</style>
